package com.college.authority.service.impl;

import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.college.authority.service.UmsResourceService;
import com.college.authority.service.UmsRoleResourceRelationService;
import com.college.authority.mapper.UmsResourceMapper;
import com.college.common.pojo.ao.UmsResource;
import com.college.common.pojo.ao.UmsRoleResourceRelation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 后台资源管理Service实现类
 * Created by macro on 2020/2/2.
 */
@Service
public class UmsResourceServiceImpl extends ServiceImpl<UmsResourceMapper, UmsResource> implements UmsResourceService {
	// @Autowired
	// private UmsAdminCacheService adminCacheService;
	@Autowired
	private UmsRoleResourceRelationService roleResourceRelationService;

	@Override
	public boolean create(UmsResource umsResource) {
		umsResource.setCreateTime(new Date());
		return save(umsResource);
	}

	@Override
	public boolean update(Long id, UmsResource umsResource) {
		umsResource.setId(id);
		boolean success = updateById(umsResource);
		// adminCacheService.delResourceListByResource(id);
		return success;
	}

	@Override
	public boolean delete(Long id) {
		// 删除前需要将所有通过角色关联的资源一并清除后再删除源资源
		boolean success = roleResourceRelationService.lambdaUpdate().eq(UmsRoleResourceRelation::getResourceId, id).remove() & removeById(id);
		// adminCacheService.delResourceListByResource(id);
		return success;
	}

	@Override
	public Page<UmsResource> list(Long categoryId, String nameKeyword, String urlKeyword, Integer pageSize, Integer pageNum) {
		Page<UmsResource> page = new Page<>(pageNum, pageSize);
		QueryWrapper<UmsResource> wrapper = new QueryWrapper<>();
		LambdaQueryWrapper<UmsResource> lambda = wrapper.lambda();
		if (categoryId != null) {
			lambda.eq(UmsResource::getCategoryId, categoryId);
		}
		if (CharSequenceUtil.isNotEmpty(nameKeyword)) {
			lambda.like(UmsResource::getName, nameKeyword);
		}
		if (CharSequenceUtil.isNotEmpty(urlKeyword)) {
			lambda.like(UmsResource::getUrl, urlKeyword);
		}
		return page(page, wrapper);
	}
}
